require 'active_support'
require 'http-access2'
require 'uri'

module Clickatell
  class Api
	  cattr_accessor :http_client, :perform_deliveries
	  cattr_accessor :base_url, :username, :password, :api_id, :phone_number

	  self.perform_deliveries = true
	  self.http_client        = HTTPAccess2::Client.new(nil, "ruby-clickatell")

	  self.base_url           = "http://api.clickatell.com/"
	  self.username           = nil
	  self.password           = nil
	  self.api_id             = nil
    self.phone_number       = nil

    # Simply yields the Clickatell::Api class itself.  This makes configuration a bit nicer looking:
    #
    #  Clickatell::Api.configure do |sms|
    #    sms.perform_deliveries = true
    #    sms.username           = 'YOUR USERNAME HERE'
    #    sms.password           = 'YOUR PASSWORD HERE'
    #    sms.api_id             = 'YOUR API ID HERE'
    #    sms.phone_number       = 'YOUR PHONE NUMBER HERE'
    #  end
    def self.configure
      yield self if block_given?
    end

    def self.send(params)
      return nil unless perform_deliveries
      params['from'] ||= self.phone_number
      request('/http/sendmsg', params)
    end

    def self.request(path, params)
      params['user'] = self.username
      params['password'] = self.password
      params['api_id'] = self.api_id

      url = URI.escape(self.base_url + path + '?' + params.map{|k, v| "#{k.to_s}=#{v.to_s}"}.join('&'))

      return self.http_client.get_async(url)
    end
  end
end
